// 模型评估页面
import React, { useState, useEffect } from 'react';
import { Layout, Card, Tabs, Typography, Space, Table, List, Tag, Statistic, Row, Col, Divider, Button, Modal, Checkbox, message, Form, Select, Progress } from 'antd';
import { mockService } from '../services/mockService';
import type { Job, Model, Metrics } from '../types';
import { formatDateTime } from '../utils/fileUtils';
import * as echarts from 'echarts';

const { Content } = Layout;
const { Title, Text } = Typography;
const { TabPane } = Tabs;

const EvaluationPage: React.FC = () => {
  const [completedJobs, setCompletedJobs] = useState<Job[]>([]);
  const [models, setModels] = useState<Model[]>([]);
  const [activeTab, setActiveTab] = useState<string>('tasks');
  const [chartRef, setChartRef] = useState<HTMLDivElement | null>(null);
  const [chartInstance, setChartInstance] = useState<echarts.ECharts | null>(null);
  const [currentJob, setCurrentJob] = useState<Job | null>(null);
  const [showResultsModal, setShowResultsModal] = useState(false);
  const [showLogsModal, setShowLogsModal] = useState(false);
  const [showFeatureSelector, setShowFeatureSelector] = useState(false);
  const [selectedFeatures, setSelectedFeatures] = useState<string[]>([]);
  const [featureCategories, setFeatureCategories] = useState<{[key: string]: string[]}>({
    classification: [],
    prediction: [],
    anomaly: []
  });
  const [selectedLogJobId, setSelectedLogJobId] = useState<string | null>(null);
  const [featureSelectForm] = Form.useForm();

  // 加载数据
  useEffect(() => {
    loadInitialData();
    
    // 设置定时刷新，每5秒更新一次数据
    const interval = setInterval(() => {
      loadInitialData();
    }, 5000);

    return () => {
      clearInterval(interval);
    };
  }, []);

  // 初始化图表
  useEffect(() => {
    if (chartRef && !chartInstance) {
      const instance = echarts.init(chartRef);
      setChartInstance(instance);
    }

    return () => {
      if (chartInstance) {
        chartInstance.dispose();
      }
    };
  }, [chartRef]);

  // 更新图表
  useEffect(() => {
    if (chartInstance && models.length > 0) {
      updateComparisonChart();
    }
  }, [models, chartInstance]);

  const loadInitialData = async () => {
    try {
      // 加载所有作业
      const jobsRes = await mockService.jobs.getAll();
      if (jobsRes.success && jobsRes.data) {
        // 筛选出评估类型的作业
        const evaluationJobs = jobsRes.data.filter(job => job.type === 'evaluation');
        setCompletedJobs(evaluationJobs);
      }
      // 加载模型
      const modelsRes = await mockService.models.getAll();
      if (modelsRes.success && modelsRes.data) {
        setModels(modelsRes.data);
      }
    } catch (error) {
      console.error('加载数据失败:', error);
    }
  };

  // 更新对比图表
  const updateComparisonChart = () => {
    if (!chartInstance || models.length === 0) return;

    const modelNames = models.map(m => m.name);
    const metrics: string[] = models.length > 0 ? Object.keys(models[0].metrics || {}) : [];
    
    const series = metrics.map(metric => ({
      name: metric,
      type: 'bar',
      data: models.map(m => m.metrics?.[metric as keyof Metrics] || 0),
      emphasis: {
        focus: 'series'
      }
    }));

    const option = {
      title: {
        text: '模型性能对比',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      legend: {
        data: metrics,
        bottom: 0
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '15%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: modelNames,
        axisLabel: {
          rotate: 45
        }
      },
      yAxis: {
        type: 'value',
        max: 1
      },
      series: series
    };

    chartInstance.setOption(option);
  };

  // 获取最佳指标
  const getBestMetric = (metric: keyof Metrics): { model: Model | null; value: number } => {
    let bestModel: Model | null = null;
    let bestValue = 0;

    models.forEach(model => {
      const value = model.metrics?.[metric] || 0;
      if (value > bestValue) {
        bestValue = value;
        bestModel = model;
      }
    });

    return { model: bestModel, value: bestValue };
  };

  // 渲染作业结果列表
  const renderJobResults = () => (
    <Card title="作业结果列表">
      <Table
        dataSource={completedJobs.filter(job => job.status === 'completed' && job.metrics)}
        columns={[
          { title: '作业名称', dataIndex: 'name', key: 'name' },
          { title: '模型类型', dataIndex: ['modelConfig', 'modelType'], key: 'modelType' },
          { 
            title: '准确率', 
            dataIndex: ['metrics', 'accuracy'], 
            key: 'accuracy',
            render: (accuracy) => accuracy ? `${(accuracy * 100).toFixed(2)}%` : '-',
            sorter: (a, b) => (a.metrics?.accuracy || 0) - (b.metrics?.accuracy || 0)
          },
          { 
            title: 'F1分数', 
            dataIndex: ['metrics', 'f1Score'], 
            key: 'f1Score',
            render: (f1) => f1 ? f1.toFixed(4) : '-',
            sorter: (a, b) => (a.metrics?.f1Score || 0) - (b.metrics?.f1Score || 0)
          },
          { 
            title: '完成时间', 
            dataIndex: 'updatedAt', 
            key: 'updatedAt',
            render: (time) => formatDateTime(time)
          }
        ]}
        rowKey="id"
        expandable={{
          expandedRowRender: (job) => (
            <Space direction="vertical" style={{ width: '100%' }}>
              <div>
                <Text strong>评估指标详情：</Text>
                <Space wrap>
                  {job.metrics && Object.entries(job.metrics).map(([key, value]) => (
                    <Tag key={key} color="blue">
                      {key}: {value?.toFixed(4)}
                    </Tag>
                  ))}
                </Space>
              </div>
              <div>
                <Text strong>模型配置：</Text>
                <pre style={{ background: '#f5f5f5', padding: '12px', borderRadius: '4px', overflow: 'auto' }}>
                  {JSON.stringify(job.modelConfig.hyperparameters, null, 2)}
                </pre>
              </div>
            </Space>
          ),
          rowExpandable: () => true,
        }}
      />
    </Card>
  );

  // 渲染模型性能对比
  const renderModelComparison = () => (
    <Card title="模型性能对比">
      {models.length === 0 ? (
        <Text type="secondary">暂无模型数据可对比</Text>
      ) : (
        <Space direction="vertical" style={{ width: '100%' }}>
          <Row gutter={16} style={{ marginBottom: '24px' }}>
            <Col span={6}>
              <Card>
                <Statistic 
                  title="最佳准确率" 
                  value={getBestMetric('accuracy').value * 100} 
                  precision={2}
                  suffix="%"
                />
                <Text type="secondary">
                  模型：{getBestMetric('accuracy').model?.name || '-'}
                </Text>
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic 
                  title="最佳F1分数" 
                  value={getBestMetric('f1Score').value} 
                  precision={4}
                />
                <Text type="secondary">
                  模型：{getBestMetric('f1Score').model?.name || '-'}
                </Text>
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic 
                  title="最佳精确率" 
                  value={getBestMetric('precision').value} 
                  precision={4}
                />
                <Text type="secondary">
                  模型：{getBestMetric('precision').model?.name || '-'}
                </Text>
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic 
                  title="最佳召回率" 
                  value={getBestMetric('recall').value} 
                  precision={4}
                />
                <Text type="secondary">
                  模型：{getBestMetric('recall').model?.name || '-'}
                </Text>
              </Card>
            </Col>
          </Row>
          
          <div style={{ height: '400px', width: '100%' }}>
            <div 
              ref={setChartRef} 
              style={{ height: '100%', width: '100%' }}
            />
          </div>
        </Space>
      )}
    </Card>
  );

  // 渲染最佳模型推荐
  const renderBestModels = () => (
    <Card title="最佳模型推荐">
      {models.length === 0 ? (
        <Text type="secondary">暂无模型数据</Text>
      ) : (
        <List
          dataSource={[
            { type: 'accuracy', title: '准确率最佳' },
            { type: 'f1Score', title: 'F1分数最佳' },
            { type: 'precision', title: '精确率最佳' },
            { type: 'recall', title: '召回率最佳' }
          ]}
          renderItem={(item) => {
            const { model, value } = getBestMetric(item.type as keyof Metrics);
            return (
              <List.Item>
                <List.Item.Meta
                  title={
                    <Space>
                      {item.title}
                      <Tag color="gold">{item.type === 'accuracy' ? `${(value * 100).toFixed(2)}%` : value.toFixed(4)}</Tag>
                    </Space>
                  }
                  description={
                    model ? (
                      <Space direction="vertical">
                        <Text strong>{model.name}</Text>
                        <Text type="secondary">{model.description}</Text>
                        <Text type="secondary">类型：{model.config.modelType}</Text>
                      </Space>
                    ) : (
                      <Text type="secondary">暂无数据</Text>
                    )
                  }
                />
              </List.Item>
            );
          }}
        />
      )}
    </Card>
  );

  // 渲染评估任务页签
  const renderEvaluationTasks = () => (
    <Card 
      title="评估任务列表"
      extra={
        <Button type="primary" onClick={handleCreateEvaluationTask}>
          创建评估任务
        </Button>
      }
    >
      <Table
        dataSource={completedJobs}
        columns={[
          { title: '任务名称', dataIndex: 'name', key: 'name' },
          { title: '模型类型', dataIndex: ['modelConfig', 'modelType'], key: 'modelType' },
          {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: (status, record) => (
              <Space direction="vertical" size="small">
                <Tag color={getStatusColor(status)}>{getStatusText(status)}</Tag>
                {status === 'pending' && (
                  <Progress percent={30} status="normal" showInfo={false} />
                )}
                {status === 'running' && (
                  <Progress percent={70} status="active" showInfo={false} />
                )}
                {status === 'completed' && (
                  <Progress percent={100} status="success" showInfo={false} />
                )}
                {status === 'failed' && (
                  <Progress percent={100} status="exception" showInfo={false} />
                )}
              </Space>
            )
          },
          { 
            title: '创建时间', 
            dataIndex: 'createdAt', 
            key: 'createdAt',
            render: (time) => formatDateTime(time)
          },
          {
            title: '操作',
            key: 'action',
            render: (_, record) => (
              <Space>
                <Button 
                  size="small" 
                  onClick={() => handleViewResults(record)}
                  disabled={record.status !== 'completed'}
                >
                  查看结果
                </Button>
                <Button 
                  size="small" 
                  onClick={() => handleViewLogs(record)}
                >
                  查看日志
                </Button>
              </Space>
            )
          }
        ]}
        rowKey="id"
        pagination={{ pageSize: 10 }}
      />
    </Card>
  );

  // 渲染评估结果页签
  const renderEvaluationResults = () => (
    <Card title="评估结果">
      {completedJobs.length === 0 ? (
        <Text type="secondary">暂无评估结果数据</Text>
      ) : (
        <>
          {renderJobResults()}
          <Divider />
          {renderModelComparison()}
          <Divider />
          {renderBestModels()}
        </>
      )}
    </Card>
  );

  // 渲染评估日志页签
  const renderEvaluationLogs = () => {
    // 找到当前选中的作业
    const selectedJob = selectedLogJobId 
      ? completedJobs.find(job => job.id === selectedLogJobId) 
      : null;
    
    return (
      <Card title="评估日志">
        {completedJobs.length === 0 ? (
          <Text type="secondary">暂无评估日志数据</Text>
        ) : (
          <>
            <Table
              dataSource={completedJobs}
              columns={[
                { title: '任务名称', dataIndex: 'name', key: 'name' },
                { title: '模型类型', dataIndex: ['modelConfig', 'modelType'], key: 'modelType' },
                { 
                  title: '状态', 
                  dataIndex: 'status', 
                  key: 'status',
                  render: (status) => <Tag color={getStatusColor(status)}>{getStatusText(status)}</Tag>
                },
                { 
                  title: '创建时间', 
                  dataIndex: 'createdAt', 
                  key: 'createdAt',
                  render: (time) => formatDateTime(time)
                },
                {
                  title: '日志',
                  key: 'logs',
                  render: (_, record) => (
                    <Button 
                      size="small" 
                      type={selectedLogJobId === record.id ? "primary" : "default"}
                      onClick={() => handleViewLogs(record)}
                    >
                      {selectedLogJobId === record.id ? "隐藏日志" : "查看日志"}
                    </Button>
                  )
                }
              ]}
              rowKey="id"
              pagination={{ pageSize: 10 }}
            />
            
            {/* 日志显示区域 */}
            {selectedJob && selectedJob.logs && selectedJob.logs.length > 0 && (
              <Card 
                title={`"${selectedJob.name}" 的日志`} 
                size="small" 
                style={{ marginTop: 16 }}
              >
                <List
                  dataSource={selectedJob.logs}
                  renderItem={(log, index) => (
                    <List.Item key={index}>
                      <Text code>{log}</Text>
                    </List.Item>
                  )}
                />
              </Card>
            )}
            
            {selectedJob && (!selectedJob.logs || selectedJob.logs.length === 0) && (
              <Card 
                title={`"${selectedJob.name}" 的日志`} 
                size="small" 
                style={{ marginTop: 16 }}
              >
                <Text type="secondary">暂无日志数据</Text>
              </Card>
            )}
          </>
        )}
      </Card>
    );
  };

  // 获取状态颜色
  const getStatusColor = (status: Job['status']) => {
    switch (status) {
      case 'pending':
        return 'default';
      case 'running':
        return 'processing';
      case 'completed':
        return 'success';
      case 'failed':
        return 'error';
      default:
        return 'default';
    }
  };

  // 获取状态文本
  const getStatusText = (status: Job['status']) => {
    switch (status) {
      case 'pending':
        return '待处理';
      case 'running':
        return '运行中';
      case 'completed':
        return '已完成';
      case 'failed':
        return '失败';
      default:
        return status;
    }
  };

  // 处理查看结果
  const handleViewResults = (job: Job) => {
    setCurrentJob(job);
    setShowResultsModal(true);
  };

  // 处理查看日志
  const handleViewLogs = (job: Job) => {
    // 如果点击的是当前已选中的日志作业，则取消选择，否则设置为当前作业
    setSelectedLogJobId(prevId => prevId === job.id ? null : job.id);
  };

  // 处理创建评估任务
  const handleCreateEvaluationTask = async () => {
    try {
      // 从mockService获取特征集数据
      const response = await mockService.datasets.getAll();
      if (response.success && response.data) {
        // 过滤出特征集数据（type为'feature'的）
        const featureDatasets = response.data.filter(dataset => dataset.type === 'feature');
        
        // 设置特征集数据用于下拉列表
        setFeatureCategories({
          classification: featureDatasets,
          prediction: [],
          anomaly: []
        });
      }
    } catch (error) {
      console.error('获取特征集数据失败:', error);
      message.error('获取特征集数据失败');
      // 出错时使用默认数据
      setFeatureCategories({
        classification: [],
        prediction: [],
        anomaly: []
      });
    }
    
    setShowFeatureSelector(true);
  };

  // 处理特征选择确认
  const handleFeatureSelectConfirm = async () => {
    try {
      const values = await featureSelectForm.validateFields();
      console.log('表单数据:', values);
      
      // 获取选中的特征集名称
      const selectedFeatureSet = featureCategories.classification.find(
        dataset => dataset.id === values.featureSet
      );
      
      // 获取选中的模型
      const selectedModels = models.filter(model => values.models.includes(model.id));
      
      // 为每个选中的模型创建一个评估任务
      const createPromises = selectedModels.map(model => {
        const newJob = {
          name: `评估-${model.name}-v${model.version}-${Date.now()}`,
          type: 'evaluation' as const,
          featureViewId: values.featureSet,
          modelConfig: {
            modelType: model.type || '评估模型',
            modelName: model.name,
            modelVersion: model.version,
            hyperparameters: model.hyperparameters || {}
          }
        };
        
        return mockService.jobs.create(newJob);
      });
      
      const results = await Promise.all(createPromises);
      
      // 检查所有任务是否创建成功
      const allSuccessful = results.every(result => result.success);
      
      if (allSuccessful) {
        message.success(`成功创建${selectedModels.length}个评估任务`);
        setShowFeatureSelector(false);
        featureSelectForm.resetFields();
        // 重新加载数据以显示新任务
        loadInitialData();
      } else {
        message.error('部分评估任务创建失败');
      }
    } catch (error) {
      console.error('表单验证失败:', error);
      message.error('请检查表单数据');
    }
  };

  // 处理特征选择取消
  const handleFeatureSelectCancel = () => {
    setShowFeatureSelector(false);
  };

  // 处理特征分类选择变化
  const handleFeatureCategoryChange = (category: string, checked: boolean) => {
    if (checked) {
      // 添加选中的特征分类
      setSelectedFeatures(prev => [...prev, category]);
    } else {
      // 移除取消选中的特征分类
      setSelectedFeatures(prev => prev.filter(feature => feature !== category));
    }
  };

  // 渲染特征集选择对话框
  const renderFeatureSelectorModal = () => {
    return (
      <Modal
        title="创建评估任务"
        open={showFeatureSelector}
        onOk={handleFeatureSelectConfirm}
        onCancel={handleFeatureSelectCancel}
        width={600}
        okText="确认"
        cancelText="取消"
      >
        <Form form={featureSelectForm} layout="vertical">
          <Form.Item
            name="featureSet"
            label="选择特征集"
            rules={[{ required: true, message: '请选择特征集' }]}
          >
            <Select placeholder="请选择特征集">
              {featureCategories.classification?.map((dataset) => (
                <Select.Option key={dataset.id} value={dataset.id}>
                  {dataset.name}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          
          <Form.Item
            name="models"
            label="选择模型（可多选）"
            rules={[{ required: true, message: '请至少选择一个模型' }]}
          >
            <Checkbox.Group>
              <Row gutter={[16, 16]}>
                {models.map((model) => (
                  <Col span={12} key={model.id}>
                    <Checkbox value={model.id}>{model.name} (v{model.version})</Checkbox>
                  </Col>
                ))}
              </Row>
            </Checkbox.Group>
          </Form.Item>
        </Form>
      </Modal>
    );
  };

  return (
    <Layout className="layout">
      <Content style={{ padding: '24px', minHeight: 'calc(100vh - 64px)' }}>
        <Title level={4}>模型评估</Title>
        <Text type="secondary">查看模型评估任务、评估结果和评估日志</Text>
        
        <Divider />
        
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <TabPane tab="评估任务" key="tasks">
            {renderEvaluationTasks()}
          </TabPane>
          <TabPane tab="评估结果" key="results">
            {renderEvaluationResults()}
          </TabPane>
          <TabPane tab="评估日志" key="logs">
            {renderEvaluationLogs()}
          </TabPane>
        </Tabs>
        
        {/* 特征集选择对话框 */}
        {renderFeatureSelectorModal()}
      </Content>
    </Layout>
  );
};

export default EvaluationPage;